﻿using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class RemoteControl : MonoBehaviour
{
    public Button RedoBtn;
    public Button UndoBtn;
    private ICommand iCommand;

    public Stack<ICommand> UndoFunctions = new Stack<ICommand>();
    public Stack<ICommand> RedoFunctions = new Stack<ICommand>();

    void Awake()
    {
        this.UndoBtn.onClick.AddListener(this.OnUnDoBtnClicked);
        this.RedoBtn.onClick.AddListener(this.OnReDoBtnClicked);
    }

    private void Update()
    {
        if (Input.GetKey(KeyCode.LeftControl) && Input.GetKeyDown(KeyCode.Z))
        {
            this.OnUnDoBtnClicked();
        }
        if (Input.GetKey(KeyCode.LeftControl) && Input.GetKeyDown(KeyCode.Y))
        {
            this.OnReDoBtnClicked();
        }
    }

    /// <summary>
    /// 执行
    /// </summary>
    public void SetCommand(ICommand iCommand1)
    {
        this.iCommand = iCommand1;
        if (this.iCommand != null)
        {
            this.iCommand.Execute();
            if (this.RedoFunctions.Count > 0)
                this.RedoFunctions.Clear();
            this.UndoFunctions.Push(this.iCommand);
        }
    }

    /// <summary>
    /// 撤销
    /// </summary>
    private void OnUnDoBtnClicked()
    {
        if (this.UndoFunctions.Count > 0)
        {
            this.iCommand = this.UndoFunctions.Peek();
            this.RedoFunctions.Push(this.iCommand);
            this.UndoFunctions.Pop().UnDo();
        }
    }

    /// <summary>
    /// 撤销
    /// </summary>
    private void OnReDoBtnClicked()
    {
        if (this.RedoFunctions.Count > 0)
        {
            this.iCommand = this.RedoFunctions.Peek();
            this.UndoFunctions.Push(this.iCommand);
            this.RedoFunctions.Pop().ReDo();
        }
    }
}
